import hashlib
import os
from typing import Optional, Tuple

from pypdf import PdfReader

from src.db import PdfIdentity


def _sha1(text: str) -> str:
    return hashlib.sha1(text.encode("utf-8", errors="ignore")).hexdigest()


def get_pdf_identity(path: str) -> Tuple[PdfIdentity, Optional[str]]:
    """
    读取 PDF，返回 PdfIdentity 与规范化的当前路径文件名（用于显示）。
    若无法读取文本，first_page_text_sha1 可能为 None。
    """
    stat = os.stat(path)
    file_size = int(stat.st_size)
    file_mtime = float(stat.st_mtime)

    reader = PdfReader(path)
    page_count = len(reader.pages)

    # Trailer /ID: list of 2 bytes-like entries; pick first as strong id if available
    doc_id: Optional[str] = None
    try:
        trailer_id = reader.trailer.get("/ID")
        if trailer_id and isinstance(trailer_id, list) and len(trailer_id) > 0:
            first_id = trailer_id[0]
            if isinstance(first_id, (bytes, bytearray)):
                doc_id = first_id.hex()
            else:
                # some PDFs may store as TextStringObject
                doc_id = str(first_id)
    except Exception:
        doc_id = None

    # Weak fingerprint: first page text sha1
    first_page_text_sha1: Optional[str] = None
    try:
        first_text = reader.pages[0].extract_text() or ""
        first_text = first_text.strip()
        if first_text:
            first_page_text_sha1 = _sha1(first_text[:10000])
    except Exception:
        first_page_text_sha1 = None

    # alt_fingerprint combines basic attributes (page_count + size) to aid diffs
    alt_fingerprint = _sha1(f"pc={page_count}|sz={file_size}")

    ident = PdfIdentity(
        doc_id=doc_id,
        alt_fingerprint=alt_fingerprint,
        page_count=page_count,
        first_page_text_sha1=first_page_text_sha1,
        file_size=file_size,
        file_mtime=file_mtime,
    )
    display_name = os.path.basename(path)
    return ident, display_name


